package cn.com.zcode.exam.service;

import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.com.zcode.core.util.ObjectUtil;
import cn.com.zcode.core.util.PdfUtil;
import cn.com.zcode.exam.model.Option;
import cn.com.zcode.exam.model.Question;

public class ImportServiceImpl2 implements ImportService {
	private static Pattern quePattern = Pattern.compile("^\\d+\\W+.*");
	private static Pattern optPattern = Pattern.compile("^[A-Z]{1}\\W+.*");
	private static Pattern indexPattern = Pattern.compile("^\\d+");
	private static Pattern indexOption = Pattern.compile("^\\w{1}");
	private static String replace_quest = "^\\d+\\W(\\s)*";
	private static String replace_option = "^\\w+\\W(\\s)*";

	private List<Question> loadAnswer(String qtext, String... aw) {
		List<Question> list = new ArrayList<Question>();
		for (String string : aw) {
			qtext = qtext.replaceAll(string, "");
		}
		qtext = qtext.trim();
		Pattern pattern = Pattern.compile("\\d+.*");
		Matcher matcher = pattern.matcher(qtext);
		if (matcher.find()) {
			int start = matcher.start();
			qtext = qtext.substring(start);
		}
		String splitQuestion = "\r\n\\s\r\n";
		String[] arr = qtext.split(splitQuestion);
//		Pattern patt = Pattern.compile("(\\d+\\.[\\s]?\r\n)[^(\\d+\\.[\\s]?\r\n)]*",Pattern.DOTALL);
//	Matcher mt = 	patt.matcher(qtext);
//		while (mt.find()) {
//			System.out.println(mt.group());
//			System.out.println("=------------------------------=");
//		}
		String string = null;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i <= arr.length; i++) {
			if (i < arr.length) {
				String temp = arr[i];
				if (!(temp = temp.trim()).isEmpty()) {
					if (Pattern.compile("^\\d+\\W+.*", Pattern.DOTALL).matcher(temp).matches()) {
						if (sb.length() > 0) {
							string = sb.toString();
							sb.delete(0, sb.length());
						}
					} 
					sb.append(temp);

				} else {
					continue;
				}
			}else{
				string = sb.toString();
			}
			if (string != null) {
				Question question = new Question();
				int qno = getQuestestNo(string);
				question.setNo(qno);
				String rno = getAnswerNo(string);
				String analys = string.replaceFirst(qno + "[\\p{Punct}\\s]?", "").replaceAll("\r", "");
				question.setAnswer(rno);
				analys = analys.replaceAll("\n", "");
				analys = analys.replaceAll("\\s*审题：\\s*", "审题：");
				analys = analys.replaceAll("\\s*解析：\\s*", "\n解析：\n");
				analys = analys.replaceAll("\\s*定位：\\s* ", "\n定位：");
				analys = analys.replaceAll("\\s*答案", "\n答案").trim();
				question.setAnalysis(analys);
				if (analys.length() - string.length() > 4) {
					System.err.println("maybe wrong.......");

				}
				list.add(question);

				string = null;

			}
		}
		return list;
	}

	private String getAnswerNo(String string) {
		String splitAnswer = "\r\n答案([\\pP‘’“”\\s])*[A-Z]";
		Pattern pattern = Pattern.compile("\\w{1}");
		Pattern answerOption = Pattern.compile(splitAnswer);
		Matcher str = answerOption.matcher(string);
		String answer = null;
		if (str.find()) {
			answer = str.group();
			Matcher matcher = pattern.matcher(answer);
			if (matcher.find()) {
				answer = matcher.group();
			}
		} else {
			System.out.println(string);
		}
		return answer;
	}

	private String filterString(String string, String[] exped) {
		if (exped != null) {
			for (String exstr : exped) {
				if ((exstr = exstr.trim()).length() > 1) {
					string = string.replaceAll(exstr, "");
				}
			}
		}
		return string;
	}

	public List<Question> loadQuestions(String string, String... exped) {

		string = filterString(string, exped);
		String[] abc = string.split("\n");
		LinkedList<Question> list = new LinkedList<Question>();
		Question question = null;
		StringBuffer sbquestion = null;
		StringBuffer sboption = null;
		int length = abc.length;
		for (int i = 0; i <= length; i++) {
			String str = (i == length) ? (sboption + "") : abc[i];
			if ((str = str.trim()).length() < 1) {
				continue;
			}

			if (maybeQuestion(str)) {
				if (sboption != null) {
					addOption(question, sboption.toString());
					sboption = null;
				}
				if (sbquestion == null) {
					sbquestion = new StringBuffer();
				}

			} else if (maybeAnswer(str)) {
				if (sbquestion != null) {
					String temp = sbquestion.toString();
					int no = getQuestestNo(temp);
					if (question == null || no != question.getNo()) {
						question = new Question();
						question.setNo(no);
						list.add(question);
					}
					addQuestion(question, temp);
					sbquestion = null;
				}
				if (sboption == null) {

					sboption = new StringBuffer();
				} else {
					addOption(question, sboption.toString());
					sboption = new StringBuffer();
				}
			}

			if (sbquestion != null) {
				sbquestion.append(str);
				sbquestion.append(" ");
			} else if (sboption != null) {
				sboption.append(str);
				sboption.append(" ");
			}

		}
		return list;
	}

	private boolean maybeQuestion(String str) {
		return quePattern.matcher(str).matches();

	}

	private boolean maybeAnswer(String str) {

		boolean boo = optPattern.matcher(str).matches();
		return boo;
	}

	private void addQuestion(Question question, String sb) {
		sb = sb.replaceFirst(replace_quest, "");

		if (question.getEnSummary() == null) {
			question.setEnSummary(sb);
		} else {
			question.setCnSummary(sb);
		}

	}

	private void addOption(Question quest, String danstr) {
		String no = getOptionNo(danstr);
		Option option = quest.getOption(no);
		if (option == null || !no.equals(option.getNo())) {
			option = new Option();
			option.setNo(no);
			quest.addOption(option);

		}
		danstr = danstr.replaceFirst(replace_option, "");
		if (option.getEnSummary() == null) {
			option.setEnSummary(danstr);
		} else {
			option.setCnSummary(danstr);

		}
	}

	private int getQuestestNo(String str) {
		Matcher matcher = indexPattern.matcher(str);
		if (matcher.find()) {
			String key = matcher.group();
			return Integer.parseInt(key);
		}
		return -1;
	}

	private String getOptionNo(String str) {
		Matcher matcher = indexOption.matcher(str);
		if (matcher.find()) {
			return matcher.group();
		}
		return null;
	}

	private List<Question> mixQuestion(List<Question> qs, List<Question> aw) {
		for (int i = 0; i < qs.size(); i++) {
			Question question = qs.get(i);
			Question answer = aw.get(i);
			if (answer != null && answer.getAnswer() != null) {
				String anstr = answer.getAnswer().trim();
				anstr.replaceAll("\\s", "");
				question.setAnalysis(answer.getAnalysis());
				question.setAnswer(anstr);
				String[] ops = anstr.split(",");
				for (String string : ops) {
					if ((string = string.trim()).length() > 0) {
						Option opt = question.getOption(string);
						opt.setCorrect(true);
					}
				}
			} else {
				System.err.println("====" + getQuestionString(answer));
			}
		}
		return qs;
	}

	@Override
	public List<Question> importQuestions(File url_quest, File url_option, String... expstr) {
		String qtext = PdfUtil.read(url_quest);
		String atext = PdfUtil.read(url_option);
		return this.importQuestions(qtext, atext, expstr);
	}

	@Override
	public List<Question> importQuestions(String qtext, String atext, String... expstr) {
		List<Question> qs = this.loadQuestions(qtext, expstr);
		List<Question> aw = this.loadAnswer(atext, expstr);
		return mixQuestion(qs, aw);

	}

	public String getQuestionString(Question question) {
		StringBuffer sb = new StringBuffer();
		append(sb, question.getNo() + " " + question.getCnSummary());
		append(sb, question.getNo() + " " + question.getEnSummary());
		for (Option opt : question.getOptions()) {
			append(sb, opt.getNo() + " " + opt.getCnSummary());
			append(sb, opt.getNo() + " " + opt.getEnSummary());
		}

		append(sb, "" + question.getAnswer());
		append(sb, "" + question.getAnalysis());
		append(sb, "=============================================");
		return sb.toString();
	}

	private StringBuffer append(StringBuffer sb, String str) {
		sb.append(str);
		sb.append("\n");
		return sb;
	}

	/**
	 * @param args
	 * @throws URISyntaxException
	 */
	public static void main(String[] args) throws Exception {
		ImportServiceImpl2 service = new ImportServiceImpl2();
		String atext = PdfUtil.getText("/q2a.pdf", "test/q2a.txt");
		String qtext = PdfUtil.getText("/q2.pdf", "test/q2.txt");
		List<Question> as = service.loadAnswer(atext, "\r\nPMP考试，不仅仅是拿到证书，更是项目管理理念的提升与进阶.*\r\n","拓展题 ","计算题 ");
		List<Question> qs = service.loadQuestions(qtext, "\r\nPMP考试，不仅仅是拿到证书，更是项目管理理念的提升与进阶.*\r\n");
		List<Question> fin = service.mixQuestion(qs, as);
		System.out.println("==>" + qs.size()+" "+as.size());
		 
		ObjectUtil.storeObject("test/q2", fin);
		// for (Question question : fin) {
		// System.out.println(question);
		// }
	
	}
	 
}
